package com.htpay.util;

import com.htpay.model.common.Constant;
import com.htpay.model.entity.Merchant;
import com.htpay.model.entity.MerchantOrder;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Random;

@Slf4j
public class MerchantUtil {

    //二维码支付过期时间：15M--单位毫秒
    public static long QR_EXPIRED_TIME = 11 * 60 * 1000;

    /**
     * 获取商户ID
     *
     * @param req
     * @return
     */
    public static Integer getMerchantId(HttpServletRequest req) {
        String token = req.getHeader(Constant.X_ACCESS_TOKEN);
        String account = JwtUtil.getClaim(token, Constant.ACCOUNT);

        //获取当前用户ID
        String id = JedisUtil.getObject(Constant.SYS_USER_INFO + account).toString();
        log.info("==== 从缓存中获取商户ID[" + id + "] ====");
        Integer merchantId = Integer.parseInt(id);

        return merchantId;
    }

    /**
     * 获取商户账号名
     *
     * @param req
     * @return
     */
    public static String getAccountName(HttpServletRequest req) {
        String token = req.getHeader(Constant.X_ACCESS_TOKEN);
        String account = JwtUtil.getClaim(token, Constant.ACCOUNT);
        return account;
    }

    /**
     * 根据用户账户产生商户Key
     *
     * @param account
     * @return
     */
    public static String generateMerchantKey(String account) {
        String prefix = ObjectConvertUtils.generateKey();
        String suffix = ObjectConvertUtils.generateKey();
        log.info("==== 产生随机字符串前8位[" + prefix + "]和后8位[" + suffix + "] ====");
        return prefix + MD5Util.getMD5String(account).substring(8, 24) + suffix;
    }

    /**
     * 商户ID
     * <p>
     * 从redis中清除
     *
     * @param username
     */
    public static void delMerchantIdFromRedis(String username) {
        //清空商户ID信息
        JedisUtil.delKey(Constant.SYS_USER_INFO + username);
    }

    /**
     * 订单前缀
     */
    private static final String ORDERPREFIX = "HT";
    /**
     * 时间戳
     */
    private static final String FORMAT = "yyyyMMddHHmmss";
    /**
     * 数字随机
     */
    public static final String numberChar = "0123456789";

    /**
     * 随机数字
     */
    public static final int numberFor = 8;

    /**
     * 动态生成内部订单
     *
     * @return
     * @author yugenhai
     */
    @NotNull
    public synchronized static String createOrderSnRandom() {
        return AbstractOrderSequenceRandomInner.createOrderSnRandomInner();
    }

    /**
     * 创建订单号<svsp + yyyy-mm-dd + Random>
     *
     * @author yugenhai
     */
    private final static class AbstractOrderSequenceRandomInner {
        private synchronized static String createOrderSnRandomInner() {
            String dateStr = DateUtils.getDate(FORMAT);
            Random random = new Random();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < numberFor; i++) {
                sb.append(numberChar.charAt(random.nextInt(numberChar.length())));
            }
            return ORDERPREFIX + dateStr + sb.toString();
        }
    }

    /**
     * 产生订单编号名称
     *
     * @return
     */
    public static String generateSubject() {
        String prefix = "HT_";
        String dateStr = DateUtils.getDate("yyMMdd");
        long curTime = System.currentTimeMillis();
        String curTimeStr = Long.toString(curTime);
        curTimeStr = curTimeStr.substring(4, curTimeStr.length() - 1);
        System.out.println(dateStr);
        System.out.println(curTimeStr);
        return prefix + dateStr + "-" + curTimeStr;
    }

    /**
     * 校验订单是否有效
     *
     * @param order
     * @return
     */
    public static boolean checkMerchantOrderValidate(MerchantOrder order) {
        if (order == null || order.getCreateTime() == null) return false;
        Date createTime = order.getCreateTime();
        long ctime = createTime.getTime();
        long ntime = System.currentTimeMillis();
        long t = ntime - ctime;
        System.out.println("=== 创建时间距离当前时间已经过了[" + (t / 60000) + "]分钟 ====");
        return t < QR_EXPIRED_TIME;
    }

    public static void main(String[] args) {
//        String subject = generateSubject();
//        System.out.println(subject);

        MerchantOrder order = new MerchantOrder();
        Date c = DateUtils.str2Date("2019-12-12 16:00:00", DateUtils.datetimeFormat);
        order.setCreateTime(c);
        boolean flag = checkMerchantOrderValidate(order);
        System.out.println(flag);
    }
}
